package com.chenjun.mysite.common;

import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

public class ControllerUtil
{
	public static <T> T getModelObject(Class<?> clazz, HttpServletRequest request)
	{
		T obj = null;
		try
		{
			obj = (T) clazz.newInstance();
			Enumeration<String> paramNames = request.getParameterNames();
			while (paramNames.hasMoreElements())
			{
				String paramName = paramNames.nextElement();
				 Method[] method =  clazz.getMethods();
				 String[] methodName = new String[method.length];
				 for(int i=0;i<method.length;i++)
				 {
					 methodName[i] = method[i].getName();
				 }
				 for(int i=0;i<methodName.length;i++)
				 {
					 
				 }
			}
		}
		catch (InstantiationException e)
		{
			e.printStackTrace();
		}
		catch (IllegalAccessException e)
		{
			e.printStackTrace();
		}

		return obj;
	}

	
	/*
	 * 获取查询参数
	 */
	public static Map<String, Object> getSearchParams(ServletRequest request,String cacheName)
	{
		Map<String, Object> searchParams = getParametersStartingWith(request, GlobalConfig.SEARCH_PARAM_PREFIX);
		//后期可以在此处加缓存
		return searchParams;
	}

	/*
	 * 根据后缀_获取查询参数
	 */
	private static Map<String, Object> getParametersStartingWith(ServletRequest request, String searchParamPrefix)
	{
		Enumeration<String> paramNames = request.getParameterNames();
		Map<String, Object> params = new TreeMap<String, Object>();
		while (paramNames.hasMoreElements())
		{
			String paramName = paramNames.nextElement();
			if ( paramName.startsWith(searchParamPrefix) )
			{
				String unprefixed = paramName.substring(searchParamPrefix.length());
				String[] values = request.getParameterValues(paramName);
				if ( (values == null) || (values.length == 0) )
				{
					// 什么都不做
				}
				else if ( values.length > 1 )
				{
					params.put(unprefixed, values);
				}
				else
				{
					params.put(unprefixed, values[0].trim());
				}
			}
		}
		return null;
	}

}
